package com.paul.sys.controller.back;

import com.paul.sys.model.Department;
import com.paul.sys.model.Ptstaff;
import com.paul.sys.service.DepartmentService;
import com.paul.sys.service.PtstaffService;

import java.util.*;

import com.paul.sys.tools.PageData;
import com.paul.sys.util.ParamUtil;
import com.paul.sys.util.TrafficMd5;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import net.sf.json.*;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by yingg_000 on 2015/7/13.
 */
@Controller
@RequestMapping("/back/user/")
public class UserController {
    private static Logger logger = Logger.getLogger(UserController.class);
    @Autowired
    private PtstaffService ptstaffService;
    @Autowired
    private DepartmentService departmentService;

    @RequestMapping("ismenu/user")
    public String role() throws Exception {
        return "back/syuser/user-list";
    }

    @ResponseBody
    @RequestMapping("edit_page")
    public ModelAndView addPage(HttpServletRequest request) {
        ModelAndView view = null;
        if (request.getParameter("unid") != null) {
            view = new ModelAndView("back/syuser/user-edit");
            Ptstaff user = ptstaffService.selectByPrimaryKey(request.getParameter("unid").toString());
            view.addObject("user", user);
            view.addObject("type", "edit");
        } else {
            view = new ModelAndView("back/syuser/user-add");

        }
        return view;
    }

    @ResponseBody
    @RequestMapping("password_page")
    public ModelAndView editPassword(HttpServletRequest request) {
        ModelAndView view = null;
        if (request.getParameter("unid") != null) {
            view = new ModelAndView("back/syuser/user-password");
            Ptstaff user = ptstaffService.selectByPrimaryKey(request.getParameter("unid").toString());
            view.addObject("user", user);
            view.addObject("type", "edit");
        } else {

        }
        return view;
    }

    @ResponseBody
    @RequestMapping("rolelink_page")
    public ModelAndView rolelinkPage(HttpServletRequest request) {
        ModelAndView view = null;
        if (request.getParameter("unid") != null) {
            view = new ModelAndView("back/syuser/user-rolelink");
            Ptstaff user = ptstaffService.selectByPrimaryKey(request.getParameter("unid").toString());
            view.addObject("user", user);
        }
        return view;
    }

    @ResponseBody
    @RequestMapping("list")
    public Map<String, Object> listPtstaff(HttpServletRequest request) {

        Map<String, Object> result = new HashMap<String, Object>();

        try {
            ParamUtil util = new ParamUtil(request);
            Map<String, String> param = util.getParamMap();
            PageData pageData = ptstaffService.listByPage(param);
            result.put("totalRows", pageData.getPageBean().getTotalNum());
            result.put("curPage", param.get("curPage"));
            result.put("data", pageData.getListData());
            result.put("success", true);
        } catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    @ResponseBody
    @RequestMapping("getAllDepartment")
    public List getAllDepartment() {
        List result = new ArrayList();
        Department entity = new Department();
        entity.setDepartid("");
        entity.setDepartname("请选择");
        result.add(entity);
        result.addAll(departmentService.listAll(new HashMap<String, String>()));
        return result;
    }

    @ResponseBody
    @RequestMapping("edit")
    public Map<String, Object> editUser(HttpServletRequest request) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            ParamUtil util = new ParamUtil(request);
            Map<String, String> param = util.getParamMap();
            //  param.put("pwd","8888");
            JSONObject jsonObject = JSONObject.fromObject(param);
            Ptstaff staff = (Ptstaff) JSONObject.toBean(jsonObject, Ptstaff.class);
            String unid = null;
            if (param.get("unid") == null) {
                  unid = UUID.randomUUID().toString();
//                 unid =String.valueOf(Integer.valueOf(ptstaffService.getUnid().
//                        get("unid")).intValue()+1);
                staff.setUnid(unid);
                String md5Pssword = TrafficMd5.md5(staff.getPwd());
                staff.setPwd(md5Pssword);
                ptstaffService.insertSelective(staff);
            } else {
                ptstaffService.updateByPrimaryKey(staff);
            }
            unid = staff.getUnid();
            result.put("unid", unid);
            result.put("status", "y");
        } catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();

            result.put("status", "n");
        }
        return result;
    }

    @ResponseBody
    @RequestMapping("delete")
    public String deleteUser(HttpServletRequest request) {
        String unids = request.getParameter("unid").toString();
        String[] unidArr = unids.split(",");
        String result = "true";
        try {
            ptstaffService.deleteByUnids(unidArr);
        } catch (Exception e) {
            result = "false";
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        return result;
    }

    @ResponseBody
    @RequestMapping("valid")
    public Map<String, Object> validUser(HttpServletRequest request) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            Map<String, String> param = new HashMap<String, String>();
            param.put("code", request.getParameter("param").toString());
            Ptstaff entity = ptstaffService.selectByCodeAndPass(param);
            if (entity == null) {
                result.put("status", "y");
                result.put("info", "验证通过!");
            } else {
                result.put("status", "n");
                result.put("info", "编号已被使用,请重新填写!");
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    @ResponseBody
    @RequestMapping("allRolesByuser")
    public Map<String, Object> listPtstaffByRole(String userunid, String username, String curPage, String pageSize) {
        Map<String, Object> result = new HashMap<String, Object>();
        Map<String, String> parm = new HashMap<String, String>();
        parm.put("userunid", userunid);
        parm.put("username", username);
        parm.put("curPage", curPage);
        parm.put("pageSize", pageSize);
        try {
            PageData<Map> pageData = ptstaffService.listRoleByUserByPage(parm, parm);
            result.put("totalRows", pageData.getPageBean().getTotalNum());
            result.put("curPage", curPage);
            result.put("data", pageData.getListData());
            result.put("success", true);
        } catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "dorolelink", method = RequestMethod.POST)
    public Map<String, Object> doRoleLink(@RequestParam String roleunid, @RequestParam String userunid, @RequestParam String enable) throws Exception {
        Map<String, Object> result = new HashMap<String, Object>();
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("roleunid", roleunid);
        param.put("userunid", userunid);
        param.put("enable", enable);
        int res = 0;
        if (enable.equals("1")) {
            res = ptstaffService.linkRole(param);
        } else {
            res = ptstaffService.unlinkRole(param);
        }
        result.put("success", true);
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "passwordedit", method = RequestMethod.POST)
    public Map<String, Object> passwordedit(@RequestParam String unid, @RequestParam String oldpassword, String newpassword) throws Exception {
        Map<String, Object> result = new HashMap<String, Object>();
        Ptstaff ptstaff = ptstaffService.selectByPrimaryKey(unid);
        oldpassword = TrafficMd5.md5(oldpassword);
        newpassword = TrafficMd5.md5(newpassword);
        String password = ptstaff.getPwd();
        if (oldpassword.equals(password)) {
            ptstaff.setPwd(newpassword);
            this.ptstaffService.updatePwd(ptstaff);
            result.put("status", true);
        } else {
            result.put("status", false);
        }
        return result;
    }
}
